package com.koicarp.agent.workflow.deepseek;

import dev.langchain4j.internal.ValidationUtils;
import dev.langchain4j.model.output.structured.Description;

import java.lang.reflect.Field;
import java.util.Locale;
import java.util.Optional;

/**
 * @Author: liuxia
 * @CreateTime: 2025/2/24 上午11:07
 * @Description: 适配deepseek返回值转换枚举
 */
public class DeepEnumOutputParser {

    private final Class<? extends Enum> enumClass;

    DeepEnumOutputParser(Class<? extends Enum> enumClass) {
        this.enumClass = (Class) ValidationUtils.ensureNotNull(enumClass, "enumClass");
    }

    public String formatInstructions() {
        try {
            Enum[] enumConstants = (Enum[])this.enumClass.getEnumConstants();
            if (enumConstants.length == 0) {
                throw new IllegalArgumentException("Should be at least one enum constant defined.");
            } else {
                StringBuilder instruction = new StringBuilder();
                // 经测试，英文的提示词准确率比中文准确率高
                instruction.append("\nYou must answer strictly with one of these enums: ");
                Enum[] var3 = enumConstants;
                int var4 = enumConstants.length;

                for(int var5 = 0; var5 < var4; ++var5) {
                    Enum enumConstant = var3[var5];
                    instruction.append("\n").append(enumConstant.name().toUpperCase(Locale.ROOT));
                    Optional<String> optionalEnumDescription = getEnumDescription(this.enumClass, enumConstant);
                    optionalEnumDescription.ifPresent((description) -> {
                        instruction.append(" - ").append(description);
                    });
                }

                return instruction.toString();
            }
        } catch (NoSuchFieldException var8) {
            NoSuchFieldException e = var8;
            throw new RuntimeException(e);
        }
    }

    static Optional<String> getEnumDescription(Class<? extends Enum> enumClass, Enum enumConstant) throws NoSuchFieldException {
        Field field = enumClass.getDeclaredField(enumConstant.name());
        if (field.isAnnotationPresent(Description.class)) {
            Description annotation = field.getAnnotation(Description.class);
            if (annotation != null) {
                return Optional.of(String.join(" ", annotation.value()));
            }
        }

        return Optional.empty();
    }

    public Enum parse(Class<? extends Enum> enumClass, String string) throws NoSuchFieldException {
        string = trimAndRemoveBracketsIfPresent(string);
        string = removeThink(string);
        Enum[] var2 = (Enum[])enumClass.getEnumConstants();
        int var3 = var2.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            Enum enumConstant = var2[var4];
            String instruction = enumConstant.name() + " - " + getEnumDescription(this.enumClass, enumConstant);
            if (enumConstant.name().equalsIgnoreCase(string) || instruction.equalsIgnoreCase(string) || string.contains(enumConstant.name())) {
                return enumConstant;
            }
        }

        throw new RuntimeException("Unknown enum value: " + string);
    }

    private String removeThink(String text) {
        String think = "</think>";
        return text.substring(text.lastIndexOf(think) + think.length());
    }

    private String trimAndRemoveBracketsIfPresent(String string) {
        string = string.trim();
        if (string.startsWith("[") && string.endsWith("]")) {
            string = string.substring(1, string.length() - 1);
        }

        return string.trim();
    }

}
